#自定义后端认证
import re
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from buluapi.apps.user.models import User

def get_user_by_phone(phone):
    try:
        user = User.objects.get(phone=phone)
        return user
    except User.DoesNotExist:
        return None


def get_user_by_account(account):
    try:
        user = User.objects.get(Q(username=account) | Q(phone=account) | Q(email=account))
        return user
    except User.DoesNotExist:
        return None

class PhoneBackend(ModelBackend):
    def authenticate(self,phone):
        #验证手机号
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return None
        
        user = get_user_by_phone(phone)
        if not user:
            return None
        
        return user
    
class AccountBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        #验证用户名和密码
        user = get_user_by_account(username)
        if user and user.check_password(password) and user.is_authenticated:
            return user
        else:
            return None
